<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1 minimum-scale=1 maximum-scale=1 user-scalable=no"/>
    <link rel="stylesheet" href="./assets/css/style.css" type="text/css"/>
    <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
    <script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
    <title>统一认证平台</title>
</head>

<body>
<div class="bottom-container">
</div>
<div id="error_box">
</div>
<div class="form-container">

    <form class="form-signin" method="post" th:action="@{/login}">
        <input type="hidden" id="loginType" name="loginType" value="imageCaptcha"/>
        <div class="welcome-text">
            <img src="./assets/img/logo.png" alt="logo" width="60">
            <span> 统一认证平台 </span>
        </div>
        <div>
            <input type="text" id="username" name="username" class="form-control" placeholder="手机 / 邮箱" required
                   onblur="leave()"/>
        </div>
        <div id="passContainer">
            <input type="password" id="password" name="password" class="form-control" placeholder="请输入密码"
                   onblur="leave()"  onchange="change(this,true)"/>
        </div>
        <div id="codeContainer" class="code-container">
            <input type="text" id="code" name="code" class="form-control" placeholder="请输入验证码"
                   onblur="leave()"  onchange="change2(this,true)"/>
            <img src="" id="code-image" onclick="getVerifyCode()"/>
        </div>
        <div style="display: none">
            <input type="text" id="uuID" name="uuID" style="display: none"/>
        </div>
        <div style="display: none; margin-bottom: 0" class="code-container" id="smsContainer">
            <input type="text" name="" class="form-control" placeholder="请输入验证码" onblur="leave()"/>
            <a id="getSmsCaptchaBtn" class="btn btn-light btn-block bg-white getCaptcha"
               href="javascript:getSmsCaptcha()">获取验证码</a>
        </div>
        <div class="change-login-type">
            <div></div>
            <a id="changeLoginType" href="javascript:showSmsCaptchaPage()">短信验证登录</a>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit"
                style="color: blue;background-color: deepskyblue">登 录
        </button>



        <div class="text-placeholder">
            第三方登录
        </div>
        <div>
            <a class="btn btn-light btn-block bg-white" href="/oauth2/authorization/gitee" role="link"
               style="text-transform: none;">
                <img width="24" style="margin-right: 5px;" alt="Gitee"
                     src="https://gitee.com/static/images/logo.svg"/>
                Github
            </a>
            <a class="btn btn-light btn-block bg-white" href="/oauth2/authorization/wechat" role="link"
               style="text-transform: none;">
                <img width="24" style="margin-right: 5px;" alt="微信登录"
                     src="https://gitee.com/static/images/logo.svg"/>
                微信登录
            </a>
        </div>


        <div id="login_container"></div>

    </form>
</div>
</body>

</html>
<script>

    //发请求获取微信扫码二维码需要参数
    //咱们在想后台的服务器发请求,获取微信扫码登录页面参数
    //还需要携带一个参数:告诉后台服务器用户授权成功以后重定向项目某一个页面
    let redirect_URL = encodeURIComponent(window.location.origin + "/wxlogin");
    let result: WXLoginResponseData = await reqWxLogin(redirect_URL);
    //生成微信扫码登录二维码页面
    //@ts-ignore
    new WxLogin({
        self_redirect: true, //true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
        id: "login_container", //显示二维码容器设置
        appid: result.data.appid, //应用位置标识appid
        scope: "snsapi_login", //当前微信扫码登录页面已经授权了
        redirect_uri: result.data.redirectUri, //填写授权回调域路径,就是用户授权成功以后，微信服务器向公司后台推送code地址
        state: result.data.state, //state就是后台服务器重定向的地址携带用户信息
        style: "black",
        href: "",
    });

    function change(id,isRequired){
        document.getElementById(id).required = isRequired;
    }

    function change2(id,isRequired){
        document.getElementById(id).required = isRequired;
    }

    function showSmsCaptchaPage() {
        // 隐藏密码框
        let passContainer = document.getElementById('passContainer');
        passContainer.style.display = 'none';
        change('passContainer',true)
        // 设置password输入框的name为空
        passContainer.children[0].setAttribute('name', '')
        // 隐藏验证码框
        let codeContainer = document.getElementById('codeContainer');
        codeContainer.style.display = 'none';
        change2('codeContainer',true)
        // 设置登录类型为短信验证码
        let loginType = document.getElementById('loginType');
        loginType.value = 'smsCaptcha';
        // 显示获取短信验证码按钮与输入框
        let smsContainer = document.getElementById('smsContainer');
        smsContainer.style.display = '';
        smsContainer.children[0].setAttribute('name', 'password')
        // 设置切换按钮文字与点击效果
        let changeLoginType = document.getElementById('changeLoginType');
        changeLoginType.innerText = '账号密码登录';
        changeLoginType.setAttribute('href', 'javascript:showPasswordPage()')
        changeLoginType.style.paddingTop = '25px';
        changeLoginType.style.paddingBottom = '5px';
    }

    function showPasswordPage() {
        // 显示密码框
        let passContainer = document.getElementById('passContainer');
        passContainer.style.display = '';
        change('passContainer',false)
        // 设置password输入框
        passContainer.children[0].setAttribute('name', 'password')
        // 显示验证码框
        let codeContainer = document.getElementById('codeContainer');
        codeContainer.style.display = '';
        change2('codeContainer',false)
        // 设置登录类型为账号密码
        let loginType = document.getElementById('loginType');
        loginType.value = 'imageCaptcha';
        // 隐藏获取短信验证码按钮与输入框
        let smsContainer = document.getElementById('smsContainer');
        smsContainer.style.display = 'none';
        smsContainer.children[0].setAttribute('name', '')
        // 设置切换按钮文字与点击效果
        let changeLoginType = document.getElementById('changeLoginType');
        changeLoginType.innerText = '短信验证登录'
        changeLoginType.setAttribute('href', 'javascript:showSmsCaptchaPage()')
        changeLoginType.style.paddingTop = '0';
    }

    function leave() {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
    }

    function getVerifyCode() {
        change('passContainer',true)
        change2('codeContainer',true)
        $.ajax({
            // 请求方式
            method: "GET",
            // 请求路径
            url: "http://127.0.0.1:8080/getCaptcha",
        })
            // 成功回调
            .then((res) => {
                document.getElementById('code-image').src = res.data
                document.getElementById("uuID").value = res.uuID;
            })
            // 失败回调
            .catch((err) => {
                console.log(err);
            });
    }

    function getSmsCaptcha() {
        let phone = document.getElementById('username').value;
        if (phone === null || phone === '' || typeof phone === 'undefined') {
            showError('手机号码不能为空.')
            return;
        }
        // 禁用按钮
        let getSmsCaptchaBtn = document.getElementById('getSmsCaptchaBtn');
        getSmsCaptchaBtn.style.pointerEvents = 'none';
        // 开始1分钟倒计时
        resetBtn(getSmsCaptchaBtn);

        $.ajax({
            // 请求方式
            type: "GET",
            data: {
                phone: phone
            },
            // 请求路径
            url: "http://127.0.0.1:8080/getSmsCaptcha",
        })
            // 成功回调
            .then((res) => {
                showSuccess('获取验证码成功.固定为：' + res.data)
            })
            // 失败回调
            .catch((err) => {
                console.log(err);
            });
    }

    /** 1分钟倒计时 **/
    function resetBtn(getSmsCaptchaBtn) {
        let s = 10;
        getSmsCaptchaBtn.innerText = '重新获取' + (--s)
        // 定时器 每隔一秒变化一次（1000ms = 1s）
        let t = setInterval(() => {
            getSmsCaptchaBtn.innerText = '重新获取' + (--s)
            if (s === 0) {
                clearInterval(t)
                getSmsCaptchaBtn.innerText = '获取验证码'
                getSmsCaptchaBtn.style.pointerEvents = '';
            }
        }, 1000);
    }

    /** 刷新页面时，调用图片验证码接口 **/
    getVerifyCode();

</script>
<script th:inline="javascript">
    function showSuccess(message) {
        let errorBox = document.getElementById("error_box");
        errorBox.innerHTML = message;
        errorBox.style.display = "block";
        errorBox.style.backgroundColor = "green"
        setTimeout(() => {
            closeError();
        }, 3000)
    }

    function showError(message) {
        let errorBox = document.getElementById("error_box");
        errorBox.innerHTML = message;
        errorBox.style.display = "block";
        errorBox.style.backgroundColor = "red"
    }

    function closeError() {
        let errorBox = document.getElementById("error_box");
        errorBox.style.display = "none";
    }

    let error = [[${ error }]]
    if (error) {
        if (window.Notification) {
            Notification.requestPermission(function () {
                if (Notification.permission === 'granted') {
                    // 用户点击了允许
                    let n = new Notification('登录失败', {
                        body: error,
                        icon: './assets/img/logo.png'
                    })
                    setTimeout(() => {
                        n.close();
                    }, 3000)
                } else {
                    showError(error);
                    setTimeout(() => {
                        closeError();
                    }, 3000)
                }
            })
        }
    }
</script>
